#include<vector>
#include<unordered_map>
using namespace std;

struct TreeNode {
     int val;
      TreeNode *left;
     TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  };

class Solution {
public:
    unordered_map<int, int> map;
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        

        for (int i = 0; i < preorder.size(); i++)
        {
            map[inorder[i]] = i;
        }

        return dfs(preorder, 0,preorder.size()-1, inorder, 0, inorder.size()-1);
    }

    TreeNode* dfs(vector<int>& preorder, int pStart, int pEnd, vector<int>& inorder, int iStart, int iEnd){
        if(pStart>pEnd || iStart>iEnd){
            return nullptr;
        }

        int iPostion = map[preorder[pStart]];
        TreeNode* head = new TreeNode(preorder[pStart]);

        head->left = dfs(preorder, pStart+1, pStart+(iPostion-iStart), inorder, iStart, iPostion-1);
        head->right = dfs(preorder, pStart+(iPostion-iStart)+1, pEnd, inorder, iPostion+1, iEnd);

        return head;
    }
};